<?php


namespace App\Services;


use Closure;
use EasyWeChat\Factory;
use Illuminate\Support\Facades\Log;

class WechatPaymentService
{
    protected $app;

    public function __construct(array $config)
    {
        $this->app = Factory::payment(array_merge($config, config('wechat.defaults')));
    }

    public function unifiedOrder(array $order)
    {
        return $this->app->order->unify($order);
    }

    public function getSdkPayConfig($prepayId)
    {
        return $this->app->jssdk->sdkConfig($prepayId);
    }

    public function paidNotify(string $paySn, Closure $closure)
    {
        return $this->app->handlePaidNotify(function ($message, $fail) use ($paySn, $closure) {
            if ($message['return_code'] !== 'SUCCESS') {
                Log::error(sprintf('支付单号【%s】微信支付回调响应失败', $paySn), $message);
                return $fail('通信失败');
            }

            return $closure($paySn, $message['transaction_id']);
        });
    }

    public function refundByTradeNo(string $tradeNo, string $refundNo, int $payAmount, int $refundAmount, array $optional = [])
    {
        return $this->app->refund->byTransactionId($tradeNo, $refundNo, $payAmount, $refundAmount, $optional);
    }

    public function refundNotify(string $refundSn, Closure $closure)
    {
        return $this->app->handleRefundedNotify(function ($message, $reqInfo, $fail) use ($refundSn, $closure) {
            if ($message['return_code'] !== 'SUCCESS') {
                Log::error(sprintf('退款单号【%s】微信退款回调响应失败', $refundSn), $message);
                return $fail('通信失败');
            }

            if ($reqInfo['refund_status'] !== 'SUCCESS') {
                Log::error(sprintf('退款单号【%s】微信退款回调响应失败', $refundSn), $reqInfo);
                return $fail($reqInfo['refund_status']);
            }

            return $closure($refundSn, $reqInfo['refund_id']);
        });
    }
}
